package com.example.word.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dict.R;
import com.example.word.adapter.UnitAdapter;
import com.example.word.bean.Browse;
import com.example.word.bean.Dict;
import com.example.word.bean.Unit;
import com.example.word.bean.Word;
import com.example.word.util.CommonUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.SPUtils;
import com.example.word.widget.ActionBar;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 词库单元
 */
public class UnitActivity extends AppCompatActivity {
    private Activity myActivity;
    private ActionBar mTitleBar;//标题栏
    private LinearLayout llEmpty;
    private RecyclerView recyclerView;
    private UnitAdapter mUnitAdapter;
    private List<Unit> mUnits = new ArrayList<>();
    private String account;
    // 每个单元单词数量
    public static final int unitCount = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unit);
        myActivity = this;
        recyclerView = findViewById(R.id.rv_unit_list);
        llEmpty = findViewById(R.id.ll_empty);
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        mTitleBar.setData(myActivity, "单元学习", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
        }
        initView();
    }

    private void initView() {
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        mUnitAdapter = new UnitAdapter(llEmpty, recyclerView);
        //=2.3、设置recyclerView的适配器
        recyclerView.setAdapter(mUnitAdapter);
        loadData();//加载数据
        mUnitAdapter.setItemListener(unit -> {
            // 查询出要学习的单词列表，单元和个数
            // 根据单元（页数），和总数进行查询
            Intent intent = new Intent(myActivity, WordStudyActivity.class);

            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("dict", unit.getDict());
            requestParam.put("dayTask", String.valueOf(unitCount));
            requestParam.put("page", String.valueOf(unit.getUnitNumber()));
            // 调用 API 客户端的方法
            HttpUtils.sendGetRequest("/getWordList", requestParam, myActivity, Word.class, response -> {
                List<Word> wordList = response.getDataList();
                List<String> wordArray = new ArrayList<>();
                for (Word word : wordList) {
                    wordArray.add(word.getWord());
                }
                intent.putExtra("wordArray", wordArray.toArray(new String[0]));
                intent.putExtra("dict", unit.getDict());

                startActivityForResult(intent, 100);
            });
        });
    }

    /**
     * 加载数据
     */
    private void loadData() {
        // 查询有多少个单元
        int wordCount = (int) getIntent().getSerializableExtra("wordCount");
        String dict = (String) getIntent().getSerializableExtra("dict");
        // 计算总页数
        int totalPages = (int) Math.ceil((double) wordCount / unitCount);

        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("dict", dict);
        requestParam.put("dayTask", String.valueOf(unitCount));
        requestParam.put("totalPages", String.valueOf(totalPages));
        // 调用 API 客户端的方法
        HttpUtils.sendGetRequest("/unitStudyCount", requestParam, myActivity, LinkedHashMap.class, response -> {
            mUnits.clear();
            for (int i = 1; i <= totalPages; i++) {
                Unit unit = new Unit();
                unit.setUnitNumber(i);
                unit.setDict(dict);

                // 查询当前页的单词学习了多少个
                unit.setStudyCount(Integer.parseInt(response.getData().get(String.valueOf(i)).toString()));

                unit.setSize(unitCount);
                if (i == totalPages) {
                    unit.setSize(wordCount % unitCount);
                }

                mUnits.add(unit);
            }
            if (mUnits != null && mUnits.size() > 0) {
                recyclerView.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
                mUnitAdapter.addItem(mUnits);
            } else {
                recyclerView.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }
}